#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "../rtai_shmem.h"

#define MAX_LINE_LEN 256

// 专用函数处理 rxpdo 映射
void load_rxpdo_config(const char *filename) {
    FILE *fp = fopen(filename, "r");
    if (!fp) {
        perror("Failed to open rxpdo file");
        exit(EXIT_FAILURE);
    }

    char line[MAX_LINE_LEN];
    int index = 0;
    
    while (fgets(line, sizeof(line), fp) && index < MAX_VAR_NUM) {
        PDOConfig *config = &shm_ptr->rxpdo[index];
        if (sscanf(line, "%u %u %u %u %u %u %u %63s",
                  &config->alias, 
                  &config->position, 
                  &config->vender_id, 
                  &config->product_code, 
                  &config->index, 
                  &config->subindex, 
                  &config->bitlen, 
                  config->name) == 8) {
            index++;
        }
    }
    fclose(fp);
    shm_ptr->rxpdo_count = index;
}

// 专用函数处理 txpdo 映射
void load_txpdo_config(const char *filename) {
    FILE *fp = fopen(filename, "r");
    if (!fp) {
        perror("Failed to open txpdo file");
        exit(EXIT_FAILURE);
    }

    char line[MAX_LINE_LEN];
    int index = 0;
    
    while (fgets(line, sizeof(line), fp) && index < MAX_VAR_NUM) {
        PDOConfig *config = &shm_ptr->txpdo[index];
        if (sscanf(line, "%u %u %u %u %u %u %u %63s",
                  &config->alias, 
                  &config->position, 
                  &config->vender_id, 
                  &config->product_code, 
                  &config->index, 
                  &config->subindex, 
                  &config->bitlen, 
                  config->name) == 8) {
            index++;
        }
    }
    fclose(fp);
    shm_ptr->txpdo_count = index;
}

void register_shm_variables(const char *filename) { 
    FILE *fp = fopen(filename, "r");
    if (!fp) {
        perror("Failed to open map_shm file");
        exit(EXIT_FAILURE);
    }

    char line[MAX_LINE_LEN];
    int zero = 0;
    
    while (fgets(line, sizeof(line), fp)) {
        // 移除换行符
        line[strcspn(line, "\n")] = 0;
        
        if (strlen(line) > 0) {
            if (shmem_register(line, TYPE_INT, &zero) < 0) {
                fprintf(stderr, "Failed to register SHM variable: %s\n", line);
            }
        }
    }
    fclose(fp);
}

int main(int argc, char **argv) {
    if (argc != 1) {
        printf("Usage: %s\n", argv[0]);
        return EXIT_FAILURE;
    }

    // 初始化用户空间共享内存
    lxrt_shmem_init();

    // 加载映射文件
    load_rxpdo_config("map_rxpdo");
    load_txpdo_config("map_txpdo");
    register_shm_variables("map_shm");

    printf("PDO mappings loaded to shared memory\n");
    return EXIT_SUCCESS;
}
